// src/stores/index.ts

import { defineStore } from 'pinia';
import router from '../router';
import type { Component } from 'vue';
import { get } from 'http';



 
 

type Modules = Record<string, () => Promise<{ default: Component }>>;
 

function stateIni(): {
  isCollapse: boolean;
  username: string;
  token_key: string;
  menuData: any[];
  tabs: { path: string; index: string; label: string; icon: string }[];
  currentMenu: any;
  permissions: any[];// 用户的权限列表
  currentPagePath: string;// 当前页面路径
  locale: string; // 当前语言
} {
  return {
    isCollapse: false,
    username: '',
    token_key: '',
    menuData: [],
    tabs: [
      {
        path: "/home",
        index: "Home",
        label: "home",
        icon: "home"
      }
    ],
    currentMenu: null,
    permissions: [], // 用户的权限列表
    currentPagePath: '/' ,// 当前页面路径
    locale: 'en' ,//当前语言默认en英语
  };
}

// 定义公共 store

export const useAllDataStore = defineStore('useAllData', {
  // 定义状态
  state: stateIni,

  // 定义 actions
  actions: {
    // 设置用户名
    setUsername(username: string) {
      this.username = username;
    },

    // 获取用户名
    getUsername(): string {
      return this.username;
    },

    // 设置 token_key
    setTokenKey(token_key: string) {
      // sessionStorage.setItem('useAllData-session-store', JSON.stringify({ token_key: token_key, menuData: this.menuData}));
      this.token_key = token_key;
    },

    // 获取 token_key
    getTokenKey(): string {
      /*
      const sessionData = sessionStorage.getItem('useAllData-session-store');
      console.log(sessionData)
      if (sessionData) {
        const data = JSON.parse(sessionData);
        this.token_key = data.token_key;
        this.menuData = data.menuData;
      }
      else
      {
        this.token_key = ''
      }
      */
      return this.token_key;
    },
    // 设置菜单数据
    setMenuData(menuData: any){
      // sessionStorage.setItem('useAllData-session-store', JSON.stringify({ token_key: this.token_key, menuData: menuData}));
      addRouter(menuData)
      this.menuData = menuData
    },
    // 获取菜单数据
    getMenuData(): [] {
      return this.menuData;
    },
    
    // tabs
    setTabsData(val: any)    
    {
      console.log('val',val)
      if(val.name==='home')
      {
        this.currentMenu=null;

      }
      else
      {
        let index=this.tabs.findIndex((item:any)=>item.index===val.index);
        console.log(index)
        index===-1?  this.tabs.push(val):"";
        console.log('tabs:',this.tabs)
   
    }
  },
    getTabsData(): [] {
      return this.tabs;
    },
    removeTagsData(val: any)
    {
      let index=this.tabs.findIndex((item:any)=>item.index===val.index);
      this.tabs.splice(index,1)
      console.log('removeTagsData',this.tabs)
    },
    resetStore()
    {
      //console.log('sessionStorage clear:', sessionStorage.length === 0); // 应该输出 true   
       
      this.$reset(); // 重置 Pinia 状态
      //console.log('sessionStorage reset:', sessionStorage.length === 0); // 应该输出 true  
     //sessionStorage.clear(); // 清空 sessionStorage
     sessionStorage.removeItem('__persisted__useAllData-store');

     //console.log('sessionStorage cleared:', sessionStorage.length === 0); // 应该输出 true  

      // Object.assign(this, stateIni()); // 复制 Pinia 状态
      // sessionStorage.removeItem('useAllData-store'); // 删除 sessionStorage 中的数据
    },
     // 登出方法
     logout() {
       this.resetStore()     
      // console.log('sessionStorage reset:', sessionStorage.length === 0); // 应该输出 true  
      // sessionStorage.removeItem('useAllData-store'); // 删除 sessionStorage 中的数据
      // console.log('sessionStorage clear:', sessionStorage.length === 0); // 应该输出 true  
      // router.push({ name: 'login' }); // 重定向到登录页面
      // 检查登录后的逻辑
      router.push({ name: 'login' }).then(() => {
        // console.log('Navigated to login page');
        // console.log('sessionStorage after navigation:', sessionStorage.length === 0); // 确认是否仍然为 true
        
      });
    },
    // 权限
    setPermissions(val: any) {
      this.permissions = val;
    },
    getPermissions(): [] {
      return this.permissions  ;
    },

    // 当前页面路径
    setCurrentPagePath(val: any) {
      this.currentPagePath = val;
    },    
    getCurrentPagePath() {
      return this.currentPagePath  ;
    },
    // 当前语言
    setLocale(val: any) {
      this.locale = val;
    },
    getLocale() {
      return this.locale  ;
    },


  },  
    persist: [{
      enabled: true,
    key: 'useAllData-store',
    storage: sessionStorage, // // localStorage  sessionStorage
    pick: ['token_key',
          'tabs',
          'menuData',
          'permissions',
          'currentPagePath'
        ], // 指定持久化的字段
    },
    {
     
    key: 'useAllData-store',
    storage: localStorage, // // localStorage  sessionStorage
    pick: ['username',
           'isCollapse',
          'locale'], // 指定持久化的字段
    },],
  

   /*persist: [
    {
      pick: ['menuData'],
      storage: localStorage,
    },
   
    {
      pick: ['token_key'],
      storage: sessionStorage,
    },
    
  ],*/
  /*
  persist: {
    enabled: true,
    key: 'useAllData-store',
    storage: sessionStorage, // // localStorage  sessionStorage
    paths: ['token_key','tabs'], // 指定持久化的字段
  },
  */
  /*
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'useAllData-store',
        storage: sessionStorage,// localStorage  sessionStorage
        paths: ['token_key','menuData'], // 指定需要持久化的字段
      },
       
    ],
  },
  */


});

function addRouter(menuData: any){
  const routerList=router.getRoutes()
  const modules: Modules = import.meta.glob('../views/**/*.vue') as Modules;
  const routerArr=[]

  menuData.forEach((item:any) => {
   // console.log(item) 
    if(item.children){
     item.children.forEach((child:any) => {
       
       const componentPath = `../${child.path}.vue`;
       
       const module = modules[componentPath];
  
       if (module) {
         /*
         module().then(({ default: component }) => {
           child.component = component;
         });
         */
         child.component = module;
         routerArr.push(child)
          
       }
     });
   }
   else
   {
     const componentPath = `../${item.path}.vue`;
     const module = modules[componentPath];
     if(module)
     {
       item.component = module;
       routerArr.push(item)
     }

   }
  });
  // 增加删除路由
  routerList.forEach((item:any) => {
    
    if (item.name === 'main' 
        || item.name === 'home' 
        || item.name === '404' 
        || item.name === 'login'
        || item.name === 'error'
        || item.name === 'undefined'
        || item.path === '/'
        || item.path === '/main') 
      return
    router.removeRoute(item.name)
  });
  
  routerArr.forEach((item:any) => {
 
   router.addRoute('main',
     {
     path: item.index,
     name: item.label,
     component: item.component,
     
   });
 
})
const routerListLast=router.getRoutes()
// console.log(routerListLast)

}

export function ReloadData() {
  const store = useAllDataStore();
  const menuData = store.getMenuData();
  addRouter(menuData);

 

}